package com.wang.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.mapper.TeacherMapper;
import com.wang.springbootinit.model.dto.teacher.TeacherAddRequest;
import com.wang.springbootinit.model.dto.teacher.TeacherEditRequest;
import com.wang.springbootinit.model.dto.teacher.TeacherQueryRequest;
import com.wang.springbootinit.model.entity.Teacher;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.model.vo.TeacherVO;
import com.wang.springbootinit.service.TeacherService;
import com.wang.springbootinit.service.UserService;
import com.wang.springbootinit.utils.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Resource
    private UserService userService;

    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public TeacherVO getCurrentTeacherInfo(HttpServletRequest request) {
        Teacher loginTeacher = userService.getLoginTeacher(request);

        // 转换为VO对象
        TeacherVO teacherVO = new TeacherVO();
        BeanUtils.copyProperties(loginTeacher, teacherVO);
        return teacherVO;
    }

    @Override
    public boolean updateTeacherInfo(TeacherEditRequest updateRequest) {
        // 获取当前登录用户ID
        Long currentTeacherId = updateRequest.getId();

        // 构建更新对象
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(updateRequest, teacher);
        teacher.setId(currentTeacherId);

        // 执行更新操作
        int rows = teacherMapper.updateById(teacher);
        return rows > 0;
    }



//    =================================管理员端=========================================================================

    @Override
    public Page<TeacherVO> getTeacherVOPage(TeacherQueryRequest teacherQueryRequest) {
        long current = teacherQueryRequest.getCurrent();
        long size = teacherQueryRequest.getPageSize();
        Page<Teacher> teacherPage = this.baseMapper.getTeacherPage(new Page<>(current, size), teacherQueryRequest);
        return convertPageToVOPage(teacherPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long addTeacher(TeacherAddRequest teacherAddRequest) {
        if (teacherAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherAddRequest, teacher);
        
        // 1. 创建教师记录
        boolean result = this.save(teacher);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "教师信息保存失败");
        }

        // 2. 创建用户账号
        User user = new User();
        user.setUserAccount(teacher.getTeacherNo());
        user.setUserName(teacher.getName());
        user.setUserRole(2);
        user.setUserPassword(DigestUtils.encrypt(teacher.getTeacherNo())); // 默认密码为工号
        user.setStudentId(teacher.getId());
        userService.save(user);

        // 3. 更新教师记录，关联用户ID
        teacher.setUserId(user.getId());
        this.updateById(teacher);

        return teacher.getId();
    }

    @Override
    public boolean updateTeacher(TeacherEditRequest teacherEditRequest) {
        if (teacherEditRequest == null || teacherEditRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherEditRequest, teacher);
        return this.updateById(teacher);
    }

    @Override
    public TeacherVO getTeacherVOById(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teacher teacher = this.getById(id);
        return convertToTeacherVO(teacher);
    }

    /**
     * 对象转换
     */
    private TeacherVO convertToTeacherVO(Teacher teacher) {
        if (teacher == null) {
            return null;
        }
        TeacherVO teacherVO = new TeacherVO();
        BeanUtils.copyProperties(teacher, teacherVO);
        // 手机号脱敏
        if (StringUtils.isNotBlank(teacher.getPhone())) {
            teacherVO.setPhone(teacher.getPhone());
        }
        return teacherVO;
    }

    /**
     * 将学生分页数据转换为VO分页数据
     */
    private Page<TeacherVO> convertPageToVOPage(Page<Teacher> teacherPage) {
        Page<TeacherVO> voPage = new Page<>(teacherPage.getCurrent(), teacherPage.getSize(), teacherPage.getTotal());
        List<TeacherVO> voList = teacherPage.getRecords().stream()
                .map(this::convertToTeacherVO)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }
}
